/* eslint-disable no-cond-assign */
/*
 * @Author       : wfl
 * @LastEditors  : wfl
 * @description  :
 * @updateInfo   :
 * @Date         : 2023-05-22 14:37:32
 * @LastEditTime : 2023-10-16 11:15:12
 */
import { ikColor } from 'iking-utils'

const replaceFillWithCssVariable = (svgData: string): string => {
  const deepColor = '--ik-main-icon-deep-color'
  const color = '--ik-main-icon-color'
  const regex = /fill="([^"]*)"/g

  let matches
  let matchIndex = 0
  let result = svgData
  result = result.replaceAll('fill="#71778D"', `fill="var(${deepColor})"`)
  result = result.replaceAll('fill="#A1A5B7"', `fill="var(${deepColor})"`)

  result = result.replaceAll('fill="#E3E4E9"', `fill="var(${color})"`)
  result = result.replaceAll('fill="#B9BAC5"', `fill="var(${color})"`)
  while ((matches = regex.exec(svgData)) !== null) {
    const fillValue = matches[1]
    if (matchIndex === 0) {
      // 第一个fill值使用深色主题颜色变量
      result = result.replace(`fill="${fillValue}"`, `fill="var(${ikColor.colorIsDark(fillValue) ? deepColor : color})"`)
    }
    else {
      // 后续fill值使用浅色主题颜色变量
      result = result.replace(`fill="${fillValue}"`, `fill="var(${ikColor.colorIsDark(fillValue) ? deepColor : color})"`)
    }
    matchIndex++
  }

  return result
}

// 将SVG数据转换为对象形式的函数，函数名为parseSvgDataToObj，输入参数为原始SVG数据字符串，返回值为以id为key值的SVG对象。
const parseSvgDataToObj = (svgData: string): Record<string, string> => {
  const pattern = /<symbol(.|\n)*?<\/symbol>/g
  const matches = svgData.match(pattern)
  if (!matches)
    return {}

  const result: Record<string, string> = {}
  const parser = new DOMParser()
  for (const match of matches) {
    const parsed = parser.parseFromString(match, 'text/xml').firstChild!
    if (!parsed || parsed.nodeName !== 'symbol')
      continue
    const id = (parsed as any).getAttribute('id')
    if (!id)
      continue
    const svgWithoutSymbol = match.replace(/<symbol[^>]*>|<\/symbol>/gi, '')
    const useVar = replaceFillWithCssVariable(svgWithoutSymbol)
    result[id] = useVar
  }
  return result
}

export default parseSvgDataToObj
